package com.gcgo.timejob;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.gcgo.zk.ServiceRegistry;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class TimeJob implements SimpleJob {
    private ZkClient zk;
    private ConcurrentHashMap<String, Long> serviceTimeMap;
    /**
     * 控制比较逻辑，第一次读取zookeeper服务器中的时间，把它保存在本地，令ready=true
     * 接着第二次读取zookeeper服务器中的时间，此时ready==true，可以与第一次存的进行比较，如果一致，证明这段时间没有请求，清零
     * 把两次查zookeeper的总时间控制在题目要求的5秒即可
     */
    private volatile boolean ready;

    public TimeJob() {
        this.zk = new ZkClient("127.0.0.1:2182");
        this.serviceTimeMap = new ConcurrentHashMap<>();
        this.ready = false;
    }

    @Override
    public void execute(ShardingContext shardingContext) {
        if (zk == null) {
            return;
        }
        //思路一：从zookeeper服务器上查两次时间，如果一致，清零
//        System.out.println("定任务执行了");
        List<String> nodeTimeList = zk.getChildren(ServiceRegistry.BASE_SERVICE + ServiceRegistry.TIME);
        if (nodeTimeList.size() != 0) {
//            System.out.println(ready);
            if (ready) {
                for (String node : nodeTimeList) {
                    Long time = zk.readData(ServiceRegistry.BASE_SERVICE + ServiceRegistry.TIME + "/" + node);
                    Long timeOld = serviceTimeMap.get(node);
                    if (time.equals(timeOld)) {
                        System.out.println("服务节点" + node + "在5秒内没有接受到请求，响应时间清零");
                        zk.writeData(ServiceRegistry.BASE_SERVICE + ServiceRegistry.TIME + "/" + node, 0L);
                    }
                }
                ready = false;
            } else {
                for (String node : nodeTimeList) {
                    Long time = zk.readData(ServiceRegistry.BASE_SERVICE + ServiceRegistry.TIME + "/" + node);
                    serviceTimeMap.put(node, time);
                }
                ready = true;
            }

        }
    }
}
